const Router = require('koa-router');
const router = new Router();
const koaBody = require('koa-body');
const path = require('path');
const fs = require('fs');
const multer = require('koa-multer');
const images = require('../model/images'); // 假设这是你保存图片路径的模型

const image_path = path.join(__dirname, '..', 'public', 'images');

// 图片显示路由
// router.get('/image/:imagesname', async ctx => {
//     const imagesname = ctx.params.imagesname;
//     const imagePathWithName = path.join(image_path, imagesname);

//     if (fs.existsSync(imagePathWithName)) {
//         ctx.body = fs.createReadStream(imagePathWithName);
//     } else {
//         console.log(imagePathWithName);
//         ctx.body = { code: '404', msg: '无法找到当前页面', path: imagePathWithName };
//     }
// });

const upload = multer({
    storage: multer.diskStorage({
        destination: function (req, file, cb) {
            const dir = "./public/images";
            if (!fs.existsSync(dir)) {
                fs.mkdirSync(dir, { recursive: true });
            }
            cb(null, dir);
        },
        filename: function (req, file, cb) {
            const ext = path.extname(file.originalname);
            const fileName = file.fieldname + "-" + Date.now() + ext;
            cb(null, fileName);
        }
    }),
    fileFilter: (req, file, cb) => {
        cb(null, true);
    }
});

router.post('/uploads', upload.single('filessss'), async (ctx) => {

    const userId = ctx.request.header.userid;

    // console.log('userid',ctx.request.header.userid)
    const file = ctx.req.file; // Note: Access the file via ctx.req.file
    // console.log('file',file);

    if (!file) {
        ctx.body = {
            code: 400,
            message: '未上传文件'
        };
        return;
    }

    // 图片相对路径
    const relativePath = `${file.filename}`;

    try {
        // 将图片路径存入数据库
        await images.saveImagePath(userId,relativePath); // 假设这是你的模型方法

        ctx.body = {
            code: 200,
            message: '图片上传成功',
            id:`${userId}`,
            url: `${relativePath}`
        };
    } catch (error) {
        ctx.body = {
            code: 500,
            message: '图片上传失败',
            error: error.message
        };
    }

    // 可以选择删除上传的文件
    // fs.unlinkSync(file.path);
});


router.get('/get-image-paths', async (ctx) => {
    try {
        const paths = await images.getImagePaths(); // 获取图片路径的模型方法
        ctx.body = {
            code: 200,
            paths
        };
    } catch (error) {
        ctx.body = {
            code: 500,
            message: '获取图片路径失败',
            error: error.message
        };
    }
});

module.exports = router;